package org.codeart.proxy.example02;

import org.codeart.proxy.example01.IUserDao;
import org.codeart.proxy.example01.UserDaoImpl;

import java.lang.reflect.Field;
import java.lang.reflect.Proxy;
import java.util.Properties;

public class ProxyFactory<T> {

    /**
     * 维护一个目标
     */
    private final T target;

    public ProxyFactory(T target) {
        this.target = target;
    }

    public T getProxyInstance() {
        return (T) Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                (proxy, method, args) -> {
                    System.out.println("开启事务");
                    Object obj = method.invoke(target, args);
                    System.out.println("提交事务");
                    return obj;
                });
    }

    public static void main(String[] args) throws IllegalAccessException, NoSuchFieldException {
//        System.getProperties().setProperty("jdk.proxy.ProxyGenerator.saveGeneratedFiles", "true");
//        System.getProperties().setProperty("sum.misc.ProxyGenerator.saveGeneratedFiles", "true");
        Field field = System.class.getDeclaredField("props");
        field.setAccessible(true);
        Properties props = (Properties) field.get(null);
        props.put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");

        IUserDao userDao = new UserDaoImpl();
        // 目标对象的信息
        System.out.println(userDao.getClass());

        ProxyFactory<IUserDao> proxyFactory = new ProxyFactory<>(userDao);
        IUserDao proxyInstance = proxyFactory.getProxyInstance();
        System.out.println(proxyInstance.getClass());
        proxyInstance.save();


    }
}
